package cn.kgc.crowd1040.fundingadmin.controller;


import cn.kgc.crowd1040.fundingadmin.pojo.Menu;
import cn.kgc.crowd1040.fundingadmin.service.MenuService;
import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gl
 * @since 2022-10-27
 */
@Controller
@RequestMapping("/menu")
public class MenuController {

    @Resource
    MenuService menuService;

    @ResponseBody
    @RequestMapping("/get/whole/tree")
    public R<List<Menu>> getWholeTree(){
        //先查出全部
        List<Menu> list = menuService.list(null);
        //建一个Map，menu.getId()为key，menu为value
        Map<Integer, Menu> map=new HashMap<>();
        for (Menu menu : list) {
            //把根节点id存到map集合中
            map.put(menu.getId(), menu);
        }
        //找到根节点
        List<Menu> rootList=new ArrayList<>();
//        Menu root=null;
        for (Menu menu : list) {
            if (menu.getPid()==null){
                rootList.add(menu);
            }else {
                //判断下级菜单的pid是否和上级菜单的id是否相同，如果相同添加到上级菜单的children属性中
                //menu->menu.pid->map的key->找到父菜单
                map.get(menu.getPid()).getChildren().add(menu);
            }
        }
        //自己组装
        return R.ok(rootList);
    }

    @RequestMapping("/to/page.html")
    public String toPage(){
        return "admin/menu-page";
    }

    @RequestMapping("/save")
    @ResponseBody
    public R<String> save(Menu menu){
        menuService.save(menu);
        return R.ok("成功");
    }
}

